package com.linln.admin.ws.service.impl;

import com.linln.admin.ws.domain.Muban;
import com.linln.admin.ws.repository.MubanRepository;
import com.linln.admin.ws.service.MubanService;
import com.linln.common.data.PageSort;
import com.linln.common.enums.StatusEnum;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author sh
 * @date 2023/01/05
 */
@Service
public class MubanServiceImpl implements MubanService {

    @Autowired
    private MubanRepository mubanRepository;

    /**
     * 根据ID查询数据
     * @param id 主键ID
     */
    @Override
    public Muban getById(Long id) {
        return mubanRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<Muban> getPageList(Example<Muban> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return mubanRepository.findAll(example, page);
    }

    /**
     * 保存数据
     * @param muban 实体对象
     */
    @Override
    public Muban save(Muban muban) {
        return mubanRepository.save(muban);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return mubanRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    public List<Muban> getAllMuBan() {

        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("status", match -> match.exact());

        Muban muban = new Muban();
        muban.setStatus(StatusEnum.OK.getCode());
        // 获取数据列表
        Example<Muban> example = Example.of(muban, matcher);
        List<Muban> mubanList = mubanRepository.findAll(example);
        if (CollectionUtils.isEmpty(mubanList)){
            return Lists.newArrayList();
        }
        return mubanList;
    }
}